"""
数据库初始化脚本
"""
from datetime import datetime
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy.orm import Session
from core.database import SessionLocal, create_tables
from core.auth import init_auth_data
from core.logging_config import get_logger
from models.user import User
from models.petition_record import PetitionRecord

logger = get_logger("init_db")


def init_sample_petition_data(db: Session):
    """初始化示例信访数据"""
    logger.info("开始初始化示例信访数据...")
    
    # 检查是否已有数据
    existing_count = db.query(PetitionRecord).count()
    if existing_count > 0:
        logger.info(f"已存在 {existing_count} 条信访记录，跳过示例数据初始化")
        return
    
    # 创建示例信访记录
    sample_records = [
        {
            "xh": "XF2024001",
            "ccjbz": "初件",
            "flnr": "环境污染",
            "tsr": "张三",
            "xfnr": "我家附近的工厂排放废气，严重影响居民健康",
            "ts_gk": "工厂废气排放问题",
            "ts_xzq": "某某省",
            "ts_ds": "某某市",
            "ts_qxs": "某某区",
            "ts_jd": "某某街道",
            "ts_dz": "某某路123号",
            "ts_qxdw": "环保局",
            "ts_dfnr": "已派工作人员前往调查",
            "djsj": datetime.strptime("2024-01-15 10:30:00", "%Y-%m-%d %H:%M:%S"),
            "ts_bz": "居民投诉"
        },
        {
            "xh": "XF2024002",
            "ccjbz": "重件",
            "flnr": "噪音污染",
            "tsr": "李四",
            "xfnr": "建筑工地夜间施工噪音太大，影响休息",
            "ts_gk": "夜间施工噪音问题",
            "ts_xzq": "某某省",
            "ts_ds": "某某市",
            "ts_qxs": "某某区",
            "ts_jd": "某某街道",
            "ts_dz": "某某路456号",
            "ts_qxdw": "城管局",
            "ts_dfnr": "已责令施工单位整改",
            "djsj": datetime.strptime("2024-01-16 14:20:00", "%Y-%m-%d %H:%M:%S"),
            "ts_bz": "重复投诉"
        },
        {
            "xh": "XF2024003",
            "ccjbz": "初件",
            "flnr": "水质污染",
            "tsr": "王五",
            "xfnr": "附近河流水质变差，有异味",
            "ts_gk": "河流水质污染问题",
            "ts_xzq": "某某省",
            "ts_ds": "某某市",
            "ts_qxs": "某某区",
            "ts_jd": "某某街道",
            "ts_dz": "某某路789号",
            "ts_qxdw": "水利局",
            "ts_dfnr": "已采样检测",
            "djsj": datetime.strptime("2024-01-17 09:15:00", "%Y-%m-%d %H:%M:%S"),
            "ts_bz": "环境投诉"
        }
    ]
    
    created_count = 0
    for record_data in sample_records:
        try:
            # 获取或创建默认用户
            user = db.query(User).filter(User.username == "admin").first()
            if not user:
                user = db.query(User).filter(User.username == "user").first()
            
            record = PetitionRecord(
                **record_data,
                creator_id=user.id if user else None
            )
            db.add(record)
            created_count += 1
        except Exception as e:
            logger.error(f"创建示例记录失败 {record_data.get('xh')}: {e}")
    
    try:
        db.commit()
        logger.info(f"成功创建 {created_count} 条示例信访记录")
    except Exception as e:
        logger.error(f"示例信访数据初始化失败: {e}")
        db.rollback()

def init_pollution_type_data(db):
    """初始化污染类型数据"""
    try:
        # 优先尝试从JSON文件导入
        json_file = "./data/pollution_types.json"
        if os.path.exists(json_file):
            logger.info(f"发现默认污染类型数据文件: {json_file}，开始导入...")
            from services.pollution_type_import_export import pollution_type_import_export

            # 使用传入的数据库会话进行导入
            result = pollution_type_import_export.import_complete_data_from_json(
                json_file,
                customer_id="default",
                clear_existing=True
            )
            logger.info(f"从JSON文件导入污染类型数据完成: {result}")
        else:
            # 如果JSON文件不存在，尝试从Excel文件导入
            excel_file = "./data/污染类型数据-待初始化.xlsx"
            if os.path.exists(excel_file):
                logger.info(f"未找到JSON文件，尝试从Excel文件导入: {excel_file}")
                from scripts.import_pollution_types_simple import SimplePollutionTypesImporter
                importer = SimplePollutionTypesImporter()
                importer.import_from_excel(excel_file, customer_id="default", clear_existing=True, db=db)
            else:
                logger.warning("未找到污染类型数据文件，跳过污染类型数据初始化")
    except Exception as e:
        logger.error(f"初始化污染类型数据失败: {e}")
        # 不抛出异常，允许数据库初始化继续进行

def init_database():
    """初始化数据库"""
    logger.info("开始初始化数据库...")
    
    # 创建数据库表
    create_tables()
    logger.info("数据库表创建完成")
    
    # 初始化认证数据
    db = SessionLocal()
    try:
        init_auth_data(db)
        logger.info("认证数据初始化完成")
        
        # 初始化示例数据
        init_sample_petition_data(db)
        logger.info("示例数据初始化完成")
        # 初始化污染类型数据
        init_pollution_type_data(db)    
        logger.info("污染类型数据初始化完成")
        
    except Exception as e:
        logger.error(f"数据初始化失败: {e}")
        db.rollback()
        raise
    finally:
        db.close()
    
    logger.info("数据库初始化完成")


if __name__ == "__main__":
    init_database()